﻿Imports System.Text
Imports System.Xml

Module frmMainHelper

    Public bStarting As Boolean = True
    Dim dtsConfig As DtsConfigClass
    Dim bChangeDetected As Boolean = False
    Dim bInEdit As Boolean = False
    Public bLoading As Boolean

    Public Sub InitFrmMain()

        Dim sVer As String = Application.ProductName & "  v" & Application.ProductVersion

        With frmMain
            .ConfigDetailsLabel.Text = ""
            '.TextBox1.Text = "C:\Projects\dCMTestPackage\dCMTestPackage\dCMTestPackageXMLConfig.dtsConfig"
            .Text = sVer
            .ConfigurationTypeComboBox.Items.Add("XML Configuration File")
            '.ConfigurationTypeComboBox.Items.Add("Environment Variable")
            '.ConfigurationTypeComboBox.Items.Add("Registry Entry")
            '.ConfigurationTypeComboBox.Items.Add("SQL Server")
            .ConfigurationTypeComboBox.SelectedIndex = 0
            .Show()
            .TextBox1.Focus()
            bStarting = False
        End With
    End Sub

    Public Sub CloseFrmMain()

        With frmMain
            If bChangeDetected Then
                MenuClick("SaveOnClose")
            End If
        End With

    End Sub

    Public Sub LoadButtonClick()

        OpenMe(frmMain.TextBox1.Text)

    End Sub

    Public Sub Button1Click()

        MenuClick("Open")

    End Sub

    Public Sub OpenMe(ByVal sFileName As String)

        dtsConfig = New DtsConfigClass
        bLoading = True

        Dim xD As Xml.XmlDocument = New Xml.XmlDocument
        Dim config As ConfigurationClass = New ConfigurationClass

        xD.Load(sFileName)

        Dim cN As Xml.XmlNode = xD.Item("DTSConfiguration").Item("DTSConfigurationHeading").Item("DTSConfigurationFileInfo")

        For Each xN As Xml.XmlNode In xD.Item("DTSConfiguration")
            If xN.Name = "Configuration" Then
                With config
                    .ConfiguredType = xN.Attributes("ConfiguredType").Value
                    .PackagePath = xN.Attributes("Path").Value
                    .ConfiguredValueType = xN.Attributes("ValueType").Value
                    .ConfiguredValue = xN.Item("ConfiguredValue").InnerText
                    dtsConfig.AddConfiguration(.ConfiguredType, .PackagePath, .ConfiguredValue, .ConfiguredValueType)
                End With
                dtsConfig.AddConfigurationDataRow(config)
            End If
        Next

        With dtsConfig
            .GeneratedBy = cN.Attributes("GeneratedBy").Value
            .GeneratedFromPackageName = cN.Attributes("GeneratedFromPackageName").Value
            .GeneratedFromPackageID = cN.Attributes("GeneratedFromPackageID").Value
            .GeneratedDate = Convert.ToDateTime(cN.Attributes("GeneratedDate").Value)
        End With

        With frmMain
            .ConfigDetailsLabel.Text = dtsConfig.returnHeaderString
            .DataGridView1.DataSource = dtsConfig.ConfigurationTable
            '.DataGridView1.Columns(0).Visible = False
            '.DataGridView1.Columns(2).Visible = False
        End With

        'Stop
        bLoading = False

    End Sub

    Public Sub RowsRemoved(ByVal r As Integer)

        If Not bLoading Then
            bChangeDetected = True
        End If

        dtsConfig.RemoveConfiguration(r)

    End Sub

    Public Sub CellValueChange(ByVal r As Integer, ByVal c As Integer)

        'Stop
        bChangeDetected = True

        Dim cell As DataGridViewCell = frmMain.DataGridView1.Item(c, r)

        Dim dt As DataTable = frmMain.DataGridView1.DataSource
        'update DtsConfig object
        With dtsConfig
            Select Case c
                Case 0
                    If Not bInEdit Then
                        bInEdit = True
                        MsgBox("Changing this value is not a valid operation.", , "Invalid Edit")
                        cell.Value = "Property"
                    Else
                        bInEdit = False
                    End If
                Case 1
                    .DtsConfigurations(r).PackagePath = dt.Rows(r).Item(c)
                Case 2
                    .DtsConfigurations(r).ConfiguredValueType = dt.Rows(r).Item(c)
                Case 3
                    .DtsConfigurations(r).ConfiguredValue = dt.Rows(r).Item(c)
            End Select
        End With

    End Sub

    Public Sub CellValidating(ByVal r As Integer, ByVal c As Integer)

        With frmMain

            Dim ctrl As Control = .DataGridView1.EditingControl
            Dim cell As DataGridViewCell = .DataGridView1.Item(c, r)

            If cell.IsInEditMode Then

                'Stop
                If c = 3 Then
                    If Not ValidateInput(.DataGridView1.Item(2, r).Value, cell.EditedFormattedValue) Then
                        MsgBox("Configuration " & .DataGridView1.Item(1, r).Value & " is not valid. Cannot convert " & cell.EditedFormattedValue & " to " & .DataGridView1.Item(2, r).Value & " data type.")
                        ctrl.Text = cell.Value
                    End If
                Else
                    Try
                        If Not ValidateInput(.DataGridView1.Item(2, r).Value, .DataGridView1.Item(3, r).Value) Then
                            MsgBox("Configuration " & .DataGridView1.Item(1, r).Value & " is not valid. Cannot convert " & .DataGridView1.Item(3, r).Value & " to " & .DataGridView1.Item(2, r).Value & " data type.")
                            Exit Sub
                        End If
                    Catch ex As Exception
                        If ex.Message = "Conversion from type 'DBNull' to type 'String' is not valid." Then
                            ' ignore
                        Else
                            Throw ex
                        End If
                    End Try
                End If
            End If
        End With

    End Sub

    Public Sub MenuClick(ByVal Action As String)

        With frmMain
            Select Case Action
                Case "Open"
                    If Strings.InStr(.TextBox1.Text, "\") > 0 Then
                        If System.IO.File.Exists(.TextBox1.Text) Then
                            .OpenFileDialog1.InitialDirectory = GetPath(.TextBox1.Text)
                            .OpenFileDialog1.FileName = .TextBox1.Text
                        Else
                            .OpenFileDialog1.InitialDirectory = GetPath(.TextBox1.Text)
                        End If
                    End If
                    .OpenFileDialog1.DefaultExt = "*.dtsConfig"
                    .OpenFileDialog1.Filter = "SSIS Configuration Files|*.dtsConfig"
                    .OpenFileDialog1.FilterIndex = 0
                    .OpenFileDialog1.ShowDialog()
                    .TextBox1.Text = .OpenFileDialog1.FileName
                    OpenMe(.TextBox1.Text)
                Case "Format"
                    If System.IO.File.Exists(.TextBox1.Text) Then
                        Dim iReply As Integer = MsgBox("Format " & .TextBox1.Text & " with XML indentation?", MsgBoxStyle.YesNoCancel, "Confirm Format Action")
                        If iReply = vbYes Then

                            dtsConfig.FormatSSISConfigFile(.TextBox1.Text)
                        End If
                    Else
                        If .TextBox1.Text = "" Then
                            MsgBox("Please enter a filename", , "Enter file name")
                        Else
                            MsgBox("Cannot locate file " & .TextBox1.Text, , "Cannot find file")
                        End If
                        .TextBox1.Focus()
                    End If
                Case "Save"
                    If dtsConfig Is Nothing Then
                        MsgBox("Please load a configuration. There is currently nothing to save.", , "No Config Loaded")
                        Exit Sub
                    End If
                    If System.IO.File.Exists(.TextBox1.Text) Then
                        Dim iReply As Integer = MsgBox("Overwrite " & .TextBox1.Text & "?", MsgBoxStyle.YesNoCancel, "Confirm File Replace")
                        If iReply = vbYes Then
                            dtsConfig.WriteMe(.TextBox1.Text)
                        End If
                        If iReply = vbNo Then
                            .SaveFileDialog1.InitialDirectory = GetPath(.TextBox1.Text)
                            .SaveFileDialog1.FileName = .TextBox1.Text
                            .SaveFileDialog1.ShowDialog()
                            .TextBox1.Text = .SaveFileDialog1.FileName
                        End If
                    Else
                        dtsConfig.WriteMe(.TextBox1.Text)
                    End If
                    bChangeDetected = False
                Case "SaveAs"
                    If dtsConfig Is Nothing Then
                        MsgBox("Please load a configuration. There is currently nothing to save.", , "No Config Loaded")
                        Exit Sub
                    End If
                    If System.IO.File.Exists(.TextBox1.Text) Then
                        .SaveFileDialog1.InitialDirectory = GetPath(.TextBox1.Text)
                        .SaveFileDialog1.FileName = .TextBox1.Text
                    End If
                    .SaveFileDialog1.ShowDialog()
                    .TextBox1.Text = .SaveFileDialog1.FileName
                    dtsConfig.WriteMe(.TextBox1.Text)
                    bChangeDetected = False
                Case "SaveOnClose"
                    If dtsConfig Is Nothing Then
                        Exit Sub
                    End If
                    If System.IO.File.Exists(.TextBox1.Text) Then
                        Dim iReply As Integer = MsgBox("Save changes?", MsgBoxStyle.YesNo, "Save Changes")
                        If iReply = vbYes Then
                            dtsConfig.WriteMe(.TextBox1.Text)
                        End If
                    End If
            End Select
        End With

    End Sub

    Public Sub WriteUpdates()
        Dim p As String = GetPath(frmMain.TextBox1.Text) & "testOut.xml"
        dtsConfig.WriteMe(p)
    End Sub

    Private Function GetPath(ByVal s As String) As String

        If System.IO.File.Exists(s) Then
            Dim iStart As Integer = InStrRev(s, "\")
            If iStart > 0 Then
                Return Strings.Left(s, iStart)
            Else
                Return ""
            End If
        Else
            Return ""
        End If

    End Function

    'Friend Function CleanInputAlphabet(ByVal str As String) As String
    '    Return System.Text.RegularExpressions.Regex.Replace(str, "[0-9\b\s-]", "")
    'End Function

    'Friend Function CleanInputNumber(ByVal str As String) As String
    '    Return System.Text.RegularExpressions.Regex.Replace(str, "[a-zA-Z\b\s-.]", "")
    'End Function

    Private Function ValidateInput(ByVal sType As String, ByVal sValue As String) As Boolean
        Select Case sType
            Case "Int32"
                If IsNumeric(sValue) Then
                    Try
                        Dim i As Int32 = Convert.ToInt32(sValue)
                        Return True
                    Catch ex As Exception
                        Return False
                    End Try
                Else
                    Return False
                End If
            Case "Boolean"
                Try
                    Dim sTmp As Boolean = Convert.ToBoolean(sValue)
                    Return True
                Catch ex As Exception
                    Return False
                End Try
            Case Else
                Return True
        End Select
    End Function

End Module
